package com.fosss.tree;

/**
 * 顺序存储二叉树
 */
public class ArrayBinaryTreeDemo {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6, 7};
        ArrayBinaryTree arrayBinaryTree=new ArrayBinaryTree(arr);
        arrayBinaryTree.preOrder();
        System.out.println();
        arrayBinaryTree.middleOrder();
        System.out.println();
        arrayBinaryTree.postOrder();
    }
}

class ArrayBinaryTree {
    private int[] arr;

    public ArrayBinaryTree(int[] arr) {
        this.arr = arr;
    }

    /**
     * 重载preOrder
     */
    public void preOrder(){
        this.preOrder(0);
    }
    public void middleOrder(){
        this.middleOrder(0);
    }
    public void postOrder(){
        this.postOrder(0);
    }

    /**
     * 前序遍历
     */
    //index为数组索引
    public void preOrder(int index) {
        //判断数组是否为空
        if (this.arr == null || this.arr.length == 0) {
            System.out.println("数组为空，无法遍历");
            return;
        }

        //进行前序遍历
        System.out.println(this.arr[index]);
        //向左遍历
        if ((2 * index + 1) < arr.length) {
            preOrder(2 * index + 1);
        }
        //向右遍历
        if ((2 * index + 2) < arr.length) {
            preOrder(2 * index + 2);
        }
    }

    /**
     * 中序遍历
     */
    //index为数组索引
    public void middleOrder(int index) {
        //判断数组是否为空
        if (this.arr == null || this.arr.length == 0) {
            System.out.println("数组为空，无法遍历");
            return;
        }

        //向左遍历
        if ((2 * index + 1) < arr.length) {
            middleOrder(2 * index + 1);
        }
        System.out.println(this.arr[index]);
        //向右遍历
        if ((2 * index + 2) < arr.length) {
            middleOrder(2 * index + 2);
        }
    }

    /**
     * 后序遍历
     */
    //index为数组索引
    public void postOrder(int index) {
        //判断数组是否为空
        if (this.arr == null || this.arr.length == 0) {
            System.out.println("数组为空，无法遍历");
            return;
        }

        //向左遍历
        if ((2 * index + 1) < arr.length) {
            postOrder(2 * index + 1);
        }
        //向右遍历
        if ((2 * index + 2) < arr.length) {
            postOrder(2 * index + 2);
        }
        System.out.println(this.arr[index]);
    }
}




























